package top.purity.framework.orm.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class RedisUtil {
    /**
     * 不设置过期时长
     */
    private static final long NOT_EXPIRE = -1;

    private final RedisTemplate<String, String> redisTemplate;

    private final ValueOperations<String, String> valueOperations;

    public Long getExpireTime(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public void delete(List<String> key) {
        if (CollUtil.isEmpty(key)) {
            return;
        }

        if (key.size() <= 1) {
            redisTemplate.delete(key.getFirst());
            return;
        }

        redisTemplate.delete(key);
    }

    public void set(String key, Object value) {
        set(key, value, getExpire());
    }

    public void set(String key, Object value, long expire){
        valueOperations.set(key, objectToJson(value));

        if(ObjUtil.notEqual(expire, NOT_EXPIRE)) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    private String objectToJson(Object object) {
        if(isBasicType(object)) {
            return String.valueOf(object);
        }

        return JSONUtil.toJsonStr(object);
    }

    private boolean isBasicType(Object object) {
        return object instanceof Integer || object instanceof Long || object instanceof Float ||
            object instanceof Double || object instanceof Boolean || object instanceof String;
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String s = valueOperations.get(key);
        if (ObjUtil.notEqual(expire, NOT_EXPIRE)) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        //将Json字符串转换为bean对象
        return StrUtil.isBlank(s) ? null : fromJson(s, clazz);
    }

    private <T> T fromJson(String json, Class<T> clazz){
        return JSONUtil.toBean(json, clazz);
    }

    private int getExpire() {
        return RandomUtil.randomInt(10, 120);
    }

}
